import { useCallback, useEffect, useRef } from 'react';

const useInterval = (
    timerHandler: () => void,
    timeout?: number,
    options?: {
        immediate?: boolean;
        manual?: boolean;
    }
) => {
    const { immediate = false, manual = false } = options || {};

    const handlerRef = useRef<() => void>();
    handlerRef.current = timerHandler;

    const intervalRef = useRef<{ intervalId: number }>({ intervalId: null });

    const clear = useCallback(() => {
        clearInterval(intervalRef.current.intervalId);
    }, []);

    const start = useCallback(() => {
        clear();

        if (typeof timeout !== 'number') {
            clear();
        }

        if (immediate) {
            handlerRef.current();
        }

        intervalRef.current.intervalId = window.setInterval(() => {
            handlerRef.current();
        }, timeout);
    }, [clear, immediate, timeout]);

    useEffect(() => {
        if (!manual) {
            start();
        }
        return clear;
    }, [clear, manual, start]);

    return [start, clear];
};

export default useInterval;
